package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession httpSession) {

        //将提交的密码password进行md5加密
        String passwordBuMd5 = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        //根据提交的用户名进行查询
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee employeeByDb = employeeService.getOne(wrapper);
        //如果没有查询到则登陆失败
        if (null == employeeByDb) {
            return R.error("用户名或密码错误！！！");
        }
        //对比密码 不一致则登陆失败
        if (!employeeByDb.getPassword().equals(passwordBuMd5)) {
            return R.error("用户名或密码错误！！！");
        }
        //查看员工是否被禁用
        if (0 == employeeByDb.getStatus()) {
            return R.error("该用户已被禁用，哈哈哈！！");
        }
        //登陆成功 将员工id存入session 并返回登陆成功
        //从数据库中获取的id  用employeeByDb的id
        httpSession.setAttribute("employeeId", employeeByDb.getId());

        return R.success(employeeByDb);
    }

    @RequestMapping("/logout")
    public R<String> logout(HttpSession httpSession) {
        httpSession.removeAttribute("employeeId");
        return R.success("退出成功");
    }

    /**
     * 添加员工
     *
     * @param httpServletRequest
     * @param employee
     * @return
     */
    @PostMapping   //1 定义post请求接收employee接口的json数据方法
    public R<String> save(HttpServletRequest httpServletRequest, @RequestBody Employee employee) {
        //2 设置初始密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        //3 设置创建时间与更新时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

//        //4 获取当前登录用户ID
//        Long employeeId = (Long) httpServletRequest.getSession().getAttribute("employeeId");

//        //5 设置创建人与更新人
//        employee.setCreateUser(employeeId);
//        employee.setUpdateUser(employeeId);
        //6 保存输入员工数据
        employeeService.save(employee);
        //7 返回操作成功
        return R.success("操作成功");
    }

    /**
     * 员工分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")  //1 定义一个get请求接收page pageSize name 参数   并导入分页插件MyBatisPlusConfig.class
    public R<Page> page(@RequestParam(required = false, defaultValue = "1") int page,
                        @RequestParam(required = false, defaultValue = "10") int pageSize,
                        String name) {
        // 2 MyBatisPlus提供的分页方法进行查询  required 判断是否是必须要有的值
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //wrapper.like 当里面的条件存在时才进行查询
        wrapper.like(StringUtils.isNotBlank(name), Employee::getName, name)
                .orderByDesc(Employee::getCreateTime);
        //调用方法查询
        Page<Employee> page1 = employeeService.page(pageInfo, wrapper);
        return R.success(page1);
    }

    /**
     * 修改员工状态
     *
     * @param httpServletRequest
     * @param employee
     * @return
     */
    @PutMapping  //1 定义一个put请求接收id与status的请求json参数
    public R<String> update(HttpServletRequest httpServletRequest, @RequestBody Employee employee) {
//        //2 获取当前用户ID
//        Long employeeId = (Long) httpServletRequest.getSession().getAttribute("employeeId");
//        //3 设置更新人与更新时间
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(employeeId);
        //4 利用MyBatis-plus提供的根据ID更新数据的方法进行数据更新
        employeeService.updateById(employee);
        //5 返回结果
        return R.success("操作成功");
        //js对long类型的数据最多精确16位，后面的会采用四舍五入导致id改变,无法成功修改
        //对象转换器JacksonObjectMapper，基于Jackson进行Java对象到json数据的互相转换
    }

    /**
     * 编辑员工
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> updateById(@PathVariable Long id) {
        Employee employee = employeeService.getById(id);
        if (null == employee) {
            return R.error("该用户不存在！！！1");
        }
        return R.success(employee);
    }


}
